package com.antaohua.tools.api.call;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.antaohua.tools.api.enums.CallMethod;
import com.antaohua.tools.api.interfaces.CallApiInterface;
import com.antaohua.tools.api.utils.HttpUtils;

@Repository
public class AliyunCall implements CallApiInterface{

	public synchronized String get(String host,String path,Map<String, String> appcode,Map<String, String> parameter) throws ClientProtocolException, IOException{
		String method = "GET";
		Map<String, String> headers = new HashMap<String, String>();
		String appCode = null;
		for (Map.Entry<String, String> entry : appcode.entrySet()) {
			if(entry.getKey().toUpperCase().equals("APPCODE")){
				appCode = entry.getValue();
			}
		 }
		
	    headers.put("Authorization", "APPCODE " + appCode);
		HttpResponse response = HttpUtils.doGet(host, path, method, headers, parameter);
		
		JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));
		if(jsonObject.getInteger("showapi_res_code")!=0){
			throw new IOException(jsonObject.getString("showapi_res_error"));
		}
		return jsonObject.getJSONObject("showapi_res_body").toString();
	}
	
	
	public synchronized String post(String host,String path,Map<String, String> appcode,Map<String, String> parameter) throws ClientProtocolException, IOException{
		String method = "POST";
		Map<String, String> headers = new HashMap<String, String>();
		String appCode = null;
		for (Map.Entry<String, String> entry : appcode.entrySet()) {
			if(entry.getKey().toUpperCase().equals("APPCODE")){
				appCode = entry.getValue();
			}
		 }
		
	    headers.put("Authorization", "APPCODE " + appCode);
		HttpResponse response = HttpUtils.doPost(host, path, method, headers, headers, parameter);

		JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));
		if(jsonObject.getInteger("showapi_res_code")!=0){
			throw new IOException(jsonObject.getString("showapi_res_error"));
		}
		return jsonObject.getJSONObject("showapi_res_body").toString();
	}


	@Override
	public String call(String host, String path, Map<String, String> appcode, Map<String, String> parameter,CallMethod method) throws ClientProtocolException, IOException {
		if(CallMethod.post.equals(method)){
			return post(host,path,appcode,parameter);
		}else{
			return get(host,path,appcode,parameter);
		}
	}


	@Override
	public String getCode() {
		return "aliyun";
	}
	
	
	
	
}
